import { Component } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import PropTypes from 'prop-types';
import { get } from 'lodash';
import { message, Modal, Popconfirm, Divider, Card, Table } from 'antd';

import styles from './Users.css';
import { PAGE_SIZE } from 'globalConstants';
import UserModal from './UserModal';
import ChangePasswordModal from './ChangePasswordModal';
import SearchForm from './SearchForm';
import CustomPagin from 'components/CustomPagin';
import { getStatusDesc } from './utils';
import auth from 'utils/auth';

let filters = {};
class Users extends Component {
  constructor(props) {
    super(props);
    this.state = {
      changePasswordUserId: null,
      editUserId: null,
      authUrl: null,
    };
  }

  pageChangeHandler = page => {
    filters = { ...filters, page };
    this.props.dispatch(
      routerRedux.push({
        pathname: '/users',
        query: filters,
      })
    );
  };

  handleSearch = params => {
    const page = 1;
    filters = { ...params, page };
    this.props.dispatch(
      routerRedux.push({
        pathname: '/users',
        query: filters,
      })
    );
  };

  handleToggleEdit = editUserId => {
    this.setState({
      editUserId,
    });
  };

  handleToggleAuthQr = authUrl => {
    this.setState({
      authUrl,
    });
  };

  handleToggleChangePassword = changePasswordUserId => {
    this.setState({
      changePasswordUserId,
    });
  };

  handleUpdateStatus = (id, status) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'users/updateStatus',
      payload: {
        id,
        status,
      },
    });
  };

  // 启用
  handleOpen = id => {
    this.handleUpdateStatus(id, 1);
  };

  // 禁用
  handleDisable = id => {
    this.handleUpdateStatus(id, 0);
  };

  handleChangePasswordOk = values => {
    const { changePasswordUserId } = this.state;
    const { dispatch, loginedUserId } = this.props;
    console.log('changeUID: ', changePasswordUserId, ' loginedUid: ', loginedUserId);

    const isSame = loginedUserId === changePasswordUserId;
    let payload = values;
    const type = isSame ? 'users/updateSelfPassword' : 'users/updatePassword';
    if (!isSame) {
      payload['id'] = changePasswordUserId;
    }

    dispatch({
      type,
      payload,
    }).then(result => {
      if (!result.code) {
        this.handleToggleChangePassword(null);
        if (isSame) {
          // 修改自己的密码后需要重新登陆
          message.success(
            '您已修改了自己的密码，需要使用新密码重新登陆',
            () => {
              auth.logout();
              dispatch(
                routerRedux.push({
                  pathname: '/login',
                })
              );
            },
            2
          );
        }
      }
    });
  };

  handleEditOk = values => {
    const { editUserId } = this.state;
    const { dispatch, loginedUserId } = this.props;

    let payload = {
      values,
    };
    let type = 'users/create';
    if (editUserId) {
      if (editUserId === loginedUserId) {
        type = 'users/updateProfile';
      } else {
        type = 'users/update';
        payload['id'] = editUserId;
      }
    }

    dispatch({
      type,
      payload,
    }).then(result => {
      if (!result.code) {
        this.handleToggleEdit(null);
        if (!editUserId) {
          // 新增用户展示google auth的二维码
          this.handleToggleAuthQr(result.data);
        }
      }
    });
  };

  render() {
    const columns = [
      {
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '手机号',
        dataIndex: 'mobile',
        key: 'mobile',
      },
      {
        title: '角色',
        dataIndex: 'role',
        key: 'role',
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        render: status => getStatusDesc(status),
      },
      {
        title: '添加时间',
        dataIndex: 'createdAt',
        key: 'createdAt',
      },
      {
        title: '操作',
        key: 'operation',
        render: (text, record) => (
          <span className={styles.operation}>
            {getStatusDesc(record.status) === '正常' && (
              <>
                <a
                  href="javascript:void(0);"
                  onClick={e => {
                    e.preventDefault();
                    this.handleToggleEdit(record.id);
                  }}>
                  编辑
                </a>
                <Divider type="vertical" key="disable" />
                <a
                  href="javascript:void(0);"
                  onClick={e => {
                    e.preventDefault();
                    this.handleToggleChangePassword(record.id);
                  }}>
                  修改密码
                </a>
                <Divider type="vertical" key="change" />
              </>
            )}
            {getStatusDesc(record.status) === '不可用' ? (
              <Popconfirm
                title="此用户已经被禁用，你确定要放开限制吗？"
                onConfirm={this.handleOpen.bind(null, record.id)}>
                <a href="javascript:void(0);">启用</a>
              </Popconfirm>
            ) : (
              <Popconfirm
                title="你确定要禁用此用户吗？"
                onConfirm={this.handleDisable.bind(null, record.id)}>
                <a href="javascript:void(0);">禁用</a>
              </Popconfirm>
            )}
          </span>
        ),
      },
    ];
    const { editUserId, authUrl, changePasswordUserId } = this.state;
    const { items: dataSource, loading, total, page: current } = this.props;
    const imgWidth = 360;

    return (
      <div className={styles.normal}>
        {editUserId !== null && (
          <UserModal
            onOk={this.handleEditOk}
            onCancel={() => {
              this.handleToggleEdit(null);
            }}
            editUserId={editUserId}
          />
        )}
        {changePasswordUserId !== null && (
          <ChangePasswordModal
            onOk={this.handleChangePasswordOk}
            onCancel={() => {
              this.handleToggleChangePassword(null);
            }}
          />
        )}
        {authUrl !== null && (
          <Modal
            width={imgWidth + 48}
            visible={true}
            onCancel={() => {
              this.handleToggleAuthQr(null);
            }}
            footer={null}>
            <Card hoverable cover={<img alt="" src={authUrl} />} style={{ width: imgWidth }}>
              <Card.Meta title="新用户认证二维码，请保管好此二维码哦" />
            </Card>
          </Modal>
        )}

        <Card className={styles.form}>
          <SearchForm
            onCreate={() => {
              this.handleToggleEdit(0);
            }}
            onSearch={this.handleSearch}
          />
        </Card>
        <Table
          bordered
          loading={loading}
          columns={columns}
          dataSource={dataSource}
          rowKey={record => record.id}
          rowClassName={(record, index) => {
            return styles[`row-status-${record.status}`];
          }}
          pagination={false}
        />
        <CustomPagin
          total={total}
          current={current}
          pageSize={PAGE_SIZE}
          onChange={this.pageChangeHandler}
        />
      </div>
    );
  }
}

if (process.env.UMI_ENV !== 'prod') {
  Users.propTypes = {
    dispatch: PropTypes.func.isRequired,
    total: PropTypes.number.isRequired,
    items: PropTypes.array.isRequired,
    page: PropTypes.number.isRequired,
    loading: PropTypes.bool.isRequired,
    loginedUserId: PropTypes.number.isRequired,
  };
}

Users.defaultProps = {
  dispatch: () => {},
  total: 0,
  items: [],
  page: 1,
  loading: false,
  loginedUserId: 0,
};

function mapStateToProps({ users, loading }) {
  const { items, total, page, loginedUser } = users;
  const loginedUserId = get(loginedUser, 'id', 0);

  return {
    items,
    total,
    page,
    loginedUserId,
    loading: loading.effects['users/fetchList'],
  };
}

export default connect(mapStateToProps)(Users);
